package cao.oschina.function.tweet;

import android.content.Context;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

import cao.oschina.R;
import cao.oschina.activity.ToolBarActivity;
import cao.oschina.api.URLs;
import cao.oschina.bean.Comment;
import cao.oschina.bean.Tweet;
import cao.oschina.util.FileUtils;
import cao.oschina.util.TimeUtil;
import cao.oschina.widget.PushDownListView;
import cao.oschina.widget.RefreshView;
import hd.util.ToastUtil;
import hd.util.adapter.BaseViewHolder;
import hd.util.adapter.UniAdapter;
import hd.util.http.HttpClient;
import hd.util.http.HttpRequestListener;
import hd.util.http.HttpResponse;
import hd.util.load.ImageLoader;
import hd.util.widget.listview.BasePushDownListView;

/**
 * 动弹
 * <p/>
 * Created by Haidy on 15/4/5.
 */
public class TweetDetail extends ToolBarActivity {

    private PushDownListView listView;
    private TweetCommentAdapter adapter;
    private boolean getAll = false;
    private int pageIndex = 0;
    private ImageLoader imageLoader;

    private Tweet tweet;

    /**
     * 初始化界面
     */
    @Override
    protected void initView() {
        configBack();
        setTitle("动弹详情");
        setBody(R.layout.tweet_detail_view);
        listView = (PushDownListView) getBody().findViewById(R.id.tween_detail_list_view);
        listView.setAdapter(adapter = new TweetCommentAdapter(getBaseContext()));
        listView.setOnRefreshListener(new PushDownListView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (!isLoading) {
                    getAll = false;
                    pageIndex = 0;
                    loadData(true);
                }
            }
        });
        listView.setOnLoadNextPageListener(new BasePushDownListView.OnLoadNextPageListener() {
            @Override
            public void onLoad() {
                if (!getAll && !isLoading) {
                    pageIndex++;
                    loadData(false);
                }
            }
        });
    }

    /**
     * 初始化数据
     */
    @Override
    protected void initData() {
        tweet = new Tweet();
        tweet.id = getIntent().getStringExtra("id");
        tweet.body = getIntent().getStringExtra("body");
        tweet.author = getIntent().getStringExtra("author");
        tweet.authorid = getIntent().getStringExtra("authorid");
        tweet.appclient = getIntent().getStringExtra("appclient");
        tweet.commentCount = getIntent().getStringExtra("commentCount");
        tweet.portrait = getIntent().getStringExtra("portrait");
        tweet.pubDate = getIntent().getStringExtra("pubDate");
        tweet.imgSmall = getIntent().getStringExtra("imgSmall");
        tweet.imgBig = getIntent().getStringExtra("imgBig");
        tweet.attach = getIntent().getStringExtra("attach");
        tweet.likeCount = getIntent().getStringExtra("likeCount");
        tweet.isLike = getIntent().getStringExtra("isLike");
        imageLoader = new ImageLoader();
        imageLoader.setImageRes(R.mipmap.ic_account_circle_grey600_36dp);
        loadData(true);
    }

    /**
     * 加载数据
     *
     * @param refresh 是否刷新
     */
    private void loadData(final boolean refresh) {
        listView.setEnabled(false);
        new HttpClient().httpGet(URLs.COMMENT_LIST + "?catalog=" + Comment.CATALOG_TWEET + "&pageSize=20&pageIndex=" + pageIndex + "&id=" + tweet.id, new HttpRequestListener() {
            @Override
            public void success(HttpResponse response) {
                List<Comment> data = Comment.parser(response.text);
                if (refresh) {
                    adapter.setData(data);
                } else {
                    if (adapter.getCount() != 0) {
                        adapter.remove(adapter.getCount() - 1);
                    }
                    if (data.size() < 20) {
                        getAll = true;
                    }
                    adapter.addAllData(data);
                }
                showTweetInfo();
                adapter.addData(null);
                listView.overHeadScroll();
                listView.setEnabled(true);
            }

            @Override
            public void failure(HttpResponse response) {
                ToastUtil.toastShort(response.info);
            }
        });
    }

    /**
     * 显示Tweet信息
     */
    private void showTweetInfo() {
        View view = View.inflate(getBaseContext(), R.layout.tweet_detail_list_header_view, null);
        listView.setHeaderView(view);
        ((TextView) view.findViewById(R.id.author)).setText(tweet.author);
        ((TextView) view.findViewById(R.id.pub_date)).setText(TimeUtil.friendTime(tweet.pubDate));
        ((TextView) view.findViewById(R.id.body)).setText(tweet.body);
        ((TextView) view.findViewById(R.id.comment_count)).setText(tweet.commentCount);
        TextView client = (TextView) view.findViewById(R.id.appclient);
        if (Integer.parseInt(tweet.appclient) == Comment.CLIENT_ANDROID) {
            client.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.ic_phone_android_grey600_18dp), null, null, null);
            client.setText(getResources().getString(R.string.android));
        } else if (Integer.parseInt(tweet.appclient) == Comment.CLIENT_IPHONE) {
            client.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.ic_phone_iphone_grey600_18dp), null, null, null);
            client.setText(getResources().getString(R.string.iphone));
        } else if (Integer.parseInt(tweet.appclient) == Comment.CLIENT_MOBILE) {
            client.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.ic_phone_android_grey600_18dp), null, null, null);
            client.setText(getResources().getString(R.string.phone));
        } else if (Integer.parseInt(tweet.appclient) == Comment.CLIENT_WINDOWS_PHONE) {
            client.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.ic_phone_android_grey600_18dp), null, null, null);
            client.setText(getResources().getString(R.string.windows_phone));
        } else {
            client.setVisibility(View.GONE);
        }
        loadImage((ImageView) view.findViewById(R.id.head_view), tweet.portrait);
    }

    private class TweetCommentAdapter extends UniAdapter<Comment, ViewHolder> {

        public TweetCommentAdapter(Context context) {
            super(context);
        }

        @Override
        public int getContentView() {
            return R.layout.comment_list_item;
        }

        @Override
        public BaseViewHolder<Comment, ViewHolder> getHolder() {
            return new BaseViewHolder<Comment, ViewHolder>() {
                @Override
                public void loadData(ViewHolder holder, Comment data, int position) {
                    if (data != null) {
                        holder.itemView.setVisibility(View.VISIBLE);
                        holder.nextPagerView.setVisibility(View.GONE);
                        holder.authorView.setText(data.author);
                        holder.pubDataView.setText(TimeUtil.friendTime(data.pubDate));
                        holder.contentView.setText(data.content);
                        holder.appClientView.setVisibility(View.VISIBLE);
                        if (data.appclient == Comment.CLIENT_ANDROID) {
                            holder.appClientView.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.ic_phone_android_grey600_18dp), null, null, null);
                            holder.appClientView.setText(getResources().getString(R.string.android));
                        } else if (data.appclient == Comment.CLIENT_IPHONE) {
                            holder.appClientView.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.ic_phone_iphone_grey600_18dp), null, null, null);
                            holder.appClientView.setText(getResources().getString(R.string.iphone));
                        } else if (data.appclient == Comment.CLIENT_MOBILE) {
                            holder.appClientView.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.ic_phone_android_grey600_18dp), null, null, null);
                            holder.appClientView.setText(getResources().getString(R.string.phone));
                        } else if (data.appclient == Comment.CLIENT_WINDOWS_PHONE) {
                            holder.appClientView.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.mipmap.ic_phone_android_grey600_18dp), null, null, null);
                            holder.appClientView.setText(getResources().getString(R.string.windows_phone));
                        } else {
                            holder.appClientView.setVisibility(View.GONE);
                        }
                        loadImage(holder.headView, data.portrait);
                    } else {
                        holder.itemView.setVisibility(View.GONE);
                        holder.nextPagerView.setVisibility(View.VISIBLE);
                        if (getAll) {
                            holder.refreshView.setVisibility(View.GONE);
                            holder.refreshTextView.setText(getString(R.string.get_all_data));
                        } else {
                            holder.refreshView.setVisibility(View.VISIBLE);
                            holder.refreshTextView.setText(getString(R.string.loading_next_pager));
                        }
                    }
                }


            };
        }

        @Override
        public ViewHolder initViewHolder(View convertView) {
            return new ViewHolder(convertView);
        }
    }

    /**
     * 加载头像
     *
     * @param headView head view
     * @param portrait 头像地址
     */
    private void loadImage(final ImageView headView, String portrait) {
        imageLoader.loadImage(portrait, headView, new ImageLoader.OnImageCacheLoaderListener() {
            @Override
            public String onSDCardCache(String url) {
                return FileUtils.getHeadImagePath(getBaseContext(), url);
            }
        });
    }

    private class ViewHolder {

        public final ImageView headView;
        public final TextView authorView;
        public final TextView pubDataView;
        public final TextView contentView;
        public final TextView appClientView;

        public final View itemView;
        public final View nextPagerView;


        public final RefreshView refreshView;
        public final TextView refreshTextView;

        public ViewHolder(View convertView) {
            itemView = convertView.findViewById(R.id.item_view);
            nextPagerView = convertView.findViewById(R.id.next_pager);

            refreshView = (RefreshView) convertView.findViewById(R.id.next_pager_refresh_view);
            refreshTextView = (TextView) convertView.findViewById(R.id.pager_text_view);

            headView = (ImageView) convertView.findViewById(R.id.head_view);
            authorView = (TextView) convertView.findViewById(R.id.author);
            pubDataView = (TextView) convertView.findViewById(R.id.pub_date);
            contentView = (TextView) convertView.findViewById(R.id.content);
            appClientView = (TextView) convertView.findViewById(R.id.appclient);
        }
    }
}
